package com.yys.gulimall.gulimallauthserver.controller;/*
 * @author zq
 */


import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.yys.common.to.user.MemberVo;
import com.yys.common.utils.R;
import com.yys.gulimall.gulimallauthserver.feign.MemberFeignService;
import com.yys.gulimall.gulimallauthserver.vo.SocialUser;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

import static com.yys.common.constant.AutherServerConstant.LOGIN_USER;

@Controller
@Log4j2
public class OAuth2Controller {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private MemberFeignService memberFeignService;

    private String client_id = "493758787";
    private String client_secret = "035fbcd1eeedbc12647d3e0f7e5bfe8f";
    private static String AUTHORIZATION_CODE = "authorization_code";
    private String redirect_uri = "http://auth.gulimall.com/oauth2.0/weibo/success";


    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam String code, HttpSession session) {

        HashMap<String, String> params = new HashMap<>();
        params.put("client_id",client_id);
        params.put("client_secret",client_secret);
        params.put("grant_type",AUTHORIZATION_CODE);
        params.put("redirect_uri",redirect_uri);
        params.put("code",code);
        //根据 code 获取accessToken
        String baseUrl = "https://api.weibo.com/oauth2/access_token";
        String sendUrl = addParamFromPostSend(baseUrl,params);

        ResponseEntity<SocialUser> responseEntity = restTemplate.postForEntity(sendUrl,null, SocialUser.class);
        HttpStatus statusCode = responseEntity.getStatusCode();
        if(statusCode.is2xxSuccessful()) {
            //成功获得accessToken
            SocialUser socialUser = responseEntity.getBody();
            if(ObjectUtils.isNotNull(socialUser)) {
                // 得到了社交用户,判断当前用户是否是新用户,若是新用户自动注册
                // 可以通过uid来区别用户, 登录或者注册
                R r = memberFeignService.socialLogin(socialUser);
                if(r.getCode() == 0) {
                    MemberVo data = r.getData(new TypeReference<MemberVo>() {});
                    session.setAttribute(LOGIN_USER,data);
                    // TODO session令牌子域名问题 session :  auth.gulimall.com -> .gulimall.com
                    // TODO session默认序列化方式存到redis , 我们希望以json方式存到redis
                    log.info("登录成功: {}",data);
                } else {
                    return "redirect:http://auth.gulimall.com/login.html";
                }
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }

        return "redirect:http://gulimall.com";
    }

    private String addParamFromPostSend(String baseUrl, HashMap<String, String> params) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(baseUrl).append("?");
        params.forEach((k,v) -> stringBuilder.append(k).append("=").append(v).append("&"));
        return stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
    }
}
